/*
 * @Author: weidewei
 * @Date: 2025-11-19 15:39:51
 * @LastEditors: weidewei
 * @LastEditTime: 2025-11-20 18:13:19
 * @Description:
 * @FilePath: \2025-front-face\vite-react-ts-template\src\pages\useTransition.tsx
 */
import styled from 'styled-components';

export default function useTransitionComp() {
  const [query, setQuery] = useState('');
  const [results, setResults] = useState([]);
  const [isPending, startTransition] = useTransition();
  const timeoutRef = useRef();
  // 处理输入变化
  const handleInputChange = (e) => {
    const value = e.target.value;
    setQuery(value);
    if (timeoutRef.current) {
      clearTimeout(timeoutRef.current);
    }
    timeoutRef.current = setTimeout(() => {
      startTransition(() => {
        performSearch(value).then(setResults);
      });
    }, 300); // 300ms防抖
  };
  async function performSearch(query) {
    // 模拟搜索API调用
    if (!query) return [];
    await new Promise((resolve) => setTimeout(resolve, 500));
    return [`结果1: ${query}`, `结果2: ${query}`, `结果3: ${query}`];
  }
  return (
    <Wrapper>
      <div className="use-transition">
        <input value={query} onChange={handleInputChange} placeholder="搜索..." />
        {/* 显示加载状态 */}
        {isPending && <div>搜索中...</div>}

        {/* 搜索结果 */}
        <ul>
          {results.map((result, index) => (
            <li key={index}>{result}</li>
          ))}
        </ul>
      </div>
    </Wrapper>
  );
}
const Wrapper = styled.div`
  .use-transition {
    color: #000;
  }
`;
